import { Link, NavLink, Outlet, useLocation, useSearchParams } from "react-router-dom";
import { getInvoices } from "../data";

export default function Invoices() {
    let invoices = getInvoices();
    let [searchParam, setSearchParam] = useSearchParams();

    /**
     * {pathname: '/invoices/1995', search: '?query=e', hash: '', state: null, key: 'e18d38c0'}
     */
    let location = useLocation();
    console.log("location", location);
  return (
    <div>
        <main style={{padding: "1rem 0"}}>
            <h2>Invoices</h2>
            {/* {
                invoices.map(invoice => (
                    <Link
                      style={{ display: "block", margin: "1rem 0" }}
                      to={`/invoices/${invoice.number}`}
                      key={invoice.number}
                    >
                      {invoice.name}
                    </Link>
                  ))
            } */}
            {/*  NavLink 动态路由*/}
            {/* {invoices.map(invoice => (
                    <NavLink
                        style={({ isActive }) => {
                        return {
                            display: "block",
                            margin: "1rem 0",
                            color: isActive ? "red" : ""
                        };
                        }}
                        to={`/invoices/${invoice.number}`}
                        key={invoice.number}
                    >
                        {invoice.name}
                    </NavLink>
            ))} */}

            {/* 搜索参数 */}

            <input value={searchParam.get('query') || ''} onChange={(e)=>{
                let filter = e.target.value;
                if(filter) {
                    setSearchParam({
                        query: filter
                    })
                } else{
                    setSearchParam({})
                }
                
                }}
            />

            {invoices.filter((invoice)=>{
                let filter = searchParam.get('query');
                if(!filter) return true;
                return invoice.name.includes(filter.toLowerCase())
            }).map(invoice => (
                    <NavLink
                        style={({ isActive }) => {
                        return {
                            display: "block",
                            margin: "1rem 0",
                            color: isActive ? "red" : ""
                        };
                        }}
                        to={`/invoices/${invoice.number}`}
                        key={invoice.number}
                    >
                        {invoice.name}
                    </NavLink>
            ))}
            <Outlet />
        </main>
    </div>
  )
}
